<?php
namespace Admin\Controller;
use Think\Controller;
class IndexController extends Controller {

  public function _initialize()
  {
    $actionName = strtolower(ACTION_NAME);
    $controllerName = strtolower(CONTROLLER_NAME);
    // dump(array('actionName'=>$actionName, 'controllerName'=>$controllerName));die;
    $AdminUser = session('admin');
    // dump($AdminUser);
    if (!in_array($actionName, array("login", 'logout')) && is_null($AdminUser)) {
      $this->error('需要登录', U('login'), 1);
      exit;
    } else {
      $AdminUser = session('admin');
      $this->assign('admin', $AdminUser);
    }
    // dump($AdminUser);die;
  }

  public function index()
  {
    $this->redirect('news');
  }


  public function newsType()
  {
    $NewsType = M('NewsType');
    $data = $NewsType->select();
    $this->assign('list', $data);
    // dump($data);
    $this->display();
  }

  public function newsTypeUpdate($id='',$name='')
  {
    if(IS_POST) {
      $NewsType = M('NewsType');
      $data['id'] = $id;
      $data['name'] = $name;
      // dump($data);
      $rs = $NewsType->data($data)->where(array('id'=>$id))->save();
      // dump($rs);die;
      if ($rs > 0) {
        $this->success('修改成功!', U('newsType'));
      } else {
        $this->error('修改失败!');
      }
      // dump($rs);die;
    } else {
      $this->id = $id;
      $this->name = $name;
      $this->display();
    }
  }

  public function news()
  {
    $News = M('News');
    $data = $News
      ->join('ckj_news_type ON ckj_news.type = ckj_news_type.id')
      ->field('ckj_news.*,ckj_news_type.name as typename')
      ->select();
    $this->assign('list', $data);
    // dump($data);
    $this->display();
  }
  public function newsAdd()
  {
    if (IS_POST) {
      $data['id'] = I('post.id');
      $data['title'] = I('post.title');
      $data['type'] = I('post.type');
      $data['pic'] = I('post.oldpic');
      $data['discrition'] = I('post.discrition');
      $data['content'] = I('post.content', '', '');
      $data['author'] = session('admin')['id'];

      // dump($data);

      $upload = new \Think\Upload();// 实例化上传类
      $upload->maxSize   =     3145728;// 设置附件上传大小
      $upload->exts      =     array('jpg', 'gif', 'png', 'jpeg');// 设置附件上传类型
      $upload->rootPath  =     './Public/Uploads/'; // 设置附件上传根目录
      $upload->savePath  =     'news/'; // 设置附件上传（子）目录
      // 上传文件 
      $info   =   $upload->upload();
      if ($info['pic']['savename'] != '') {
        $data['pic'] = '/Public/Uploads/' . $info['pic']['savepath'] . $info['pic']['savename'];
      }
      // dump($info);

      $News = M('News');
      
      if (isset($data['id']) && $data['id'] > 0) {
        // dump('修改');
        // dump($data);
        $data['updatetime'] = time();
        // die;
        $rs = $News->data($data)->save();
      } else {
        // dump('新增');
        // dump($data);
        // die;
        $rs = $News->data($data)->add();
      }
      // dump($rs);
      if ($rs) {
        $this->success('保存成功!', U('news'));
      } else {
        $this->error('保存失败!');
      }
      
    } else {
      $NewsType = M('NewsType');
      $data = $NewsType->select();
      $this->newstype = $data;
      $this->display();
    }
  }

  public function newsUpdate($id='')
  {
    if (IS_POST) {
      # code...
    } else {
      if($id!='') {
        $NewsType = M('NewsType');
        $typeList = $NewsType->select();
        $this->newstype = $typeList;

        $News = M('News');
        $data = $News->where(array('id'=>$id))->find();
        // dump($data);
        $this->news = $data;
        $this->display();
      } else {
        $this->error('参数错误!', U('news'));
      }
    }
  }

  public function newsDelete($id='')
  {
    if(isset($id)) {
      $News = M('News');
      $rs = $News->where(array('id'=>$id))->delete();
      // dump($rs);
      if ($rs == 1) {
        $this->success('删除成功!', U('news'));
      } else {
        $this->error('删除失败!');
      }
    } else {
      $this->error('参数错误!');
    }
  }


  // 宝石相关
  public function gem()
  {
    $Gem = M('Gem');
    $data = $Gem
      // ->join('ckj_gem_type1 ON ckj_gem.type = ckj_gem_type1.id')
      // ->field('ckj_gem.*,ckj_gem_type1.name as type1name')
      ->select();
    $this->assign('list', $data);
    // dump($data);
    $this->display();
  }

  public function gemAdd()
  {
    if (IS_POST) {
      $data['id'] = I('post.id');
      $data['title'] = I('post.title');
      $data['type1'] = I('post.type1');
      $data['type2'] = I('post.type2');
      $data['pricetype'] = I('post.ptype');
      $data['weighttype'] = I('post.wtype');
      $data['certificatetype'] = I('post.ctype');
      $data['oldpic'] = I('post.oldpic');
      $data['summary'] = I('post.summary');
      $data['price'] = I('post.price');
      $data['content'] = I('post.content', '', '');
      $data['author'] = session('admin')['id'];

      // dump($data);

      $upload = new \Think\Upload();// 实例化上传类
      $upload->maxSize   =     20*1024*1024;// 设置附件上传大小
      $upload->exts      =     array('jpg', 'gif', 'png', 'jpeg');// 设置附件上传类型
      $upload->rootPath  =     './Public/Uploads/'; // 设置附件上传根目录
      $upload->saveName  =     'getSaveName';//文件名称设置（系统时间戳+随机数）  
      $upload->savePath  =     'gem/'; // 设置附件上传（子）目录
      // 上传文件 
      $info   =   $upload->upload();
      // dump($info);
      // dump($upload->getError());
      // die;
      
      $infoLen = sizeof($info);
      $picArr = array();
      for ($i=0; $i < $infoLen; $i++) {
        // dump('savename:'. $info[$i]['savename']);
        if ($info[$i]['key'] == 'pic' && $info[$i]['savename'] != '') {
          $picArr[$i] = '/Public/Uploads/' . $info[$i]['savepath'] . $info[$i]['savename'];
          // array_push($picArr, '/Public/Uploads/' . $info['pic']['savepath'] . $info['pic']['savename']);
        }
      }
      // dump($picArr);
      $data['pic'] = implode(',', $picArr);

      $Gem = M('Gem');
      
      if (isset($data['id']) && $data['id'] > 0) {
        // dump('修改');
        // dump($data);
        $data['updatetime'] = time();
        // dump($data['pic'] == '');die;
        if ($data['pic'] == '') {
          $data['pic'] = $data['oldpic'];
        }
        // die;
        $rs = $Gem->data($data)->where(array('id'=>$data['id']))->save();
      } else {
        // dump('新增');
        if ($data['pic'] == '') {
          $data['pic'] = $data['oldpic'];
        }
        // dump($data);
        // die;
        $rs = $Gem->data($data)->add();
      }
      // dump($rs);
      if ($rs) {
        $this->success('保存成功!', U('gem'));
      } else {
        $this->error('保存失败!');
      }
      
    } else {
      $GemType1 = M('GemType1');
      $t1 = $GemType1->select();
      $this->type1 = $t1;
      
      $GemType2 = M('GemType2');
      $t2 = $GemType2->select();
      $this->type2 = $t2;
      
      $PriceType = M('PriceType');
      $pt = $PriceType->select();
      $this->ptype = $pt;
      
      $WeightType = M('WeightType');
      $wt = $WeightType->select();
      $this->wtype = $wt;
      
      $CertificateType = M('CertificateType');
      $ct = $CertificateType->select();
      $this->ctype = $ct;
      $this->display();
    }
  }

  public function gemUpdate($id='')
  {
    if (IS_POST) {
      # code...
    } else {
      if($id!='') {
        $GemType1 = M('GemType1');
        $t1 = $GemType1->select();
        $this->type1 = $t1;
        
        $GemType2 = M('GemType2');
        $t2 = $GemType2->select();
        $this->type2 = $t2;
        
        $PriceType = M('PriceType');
        $pt = $PriceType->select();
        $this->ptype = $pt;
        
        $WeightType = M('WeightType');
        $wt = $WeightType->select();
        $this->wtype = $wt;
        
        $CertificateType = M('CertificateType');
        $ct = $CertificateType->select();
        $this->ctype = $ct;

        $Gem = M('Gem');
        $data = $Gem->where(array('id'=>$id))->find();
        // dump($data);
        $this->gem = $data;
        $this->display();
      } else {
        $this->error('参数错误!', U('gem'));
      }
    }
  }

  public function gemDelete($id='')
  {
    if($id) {
      $Gem = M('Gem');
      $rs = $Gem->where(array('id'=>$id))->delete();
      if ($rs) {
        $this->success('删除成功', U('gem'));
      } else {
        $this->error('删除失败', U('gem'));
      }
    } else {
      $this->error('参数错误!', U('gem'), 1);
    }
  }

  public function gemType1()
  {
    $GemType1 = M('GemType1');
    $data = $GemType1->select();
    $this->assign('list', $data);
    // dump($data);
    $this->display();
  }
  public function gemType1Update($id='',$name='')
  {
    if(IS_POST) {
      $GemType1 = M('GemType1');
      $data['id'] = $id;
      $data['name'] = $name;
      // dump($data);
      $rs = $GemType1->data($data)->where(array('id'=>$id))->save();
      // dump($rs);die;
      if ($rs > 0) {
        $this->success('修改成功!', U('gemType1'));
      } else {
        $this->error('修改失败!');
      }
      // dump($rs);die;
    } else {
      $this->id = $id;
      $this->name = $name;
      $this->display();
    }
  }
  
  public function gemType2()
  {
    $GemType2 = M('GemType2');
    $data = $GemType2->select();
    $this->assign('list', $data);
    // dump($data);
    $this->display();
  }
  public function gemType2Update($id='',$name='')
  {
    if(IS_POST) {
      $GemType2 = M('GemType2');
      $data['id'] = $id;
      $data['name'] = $name;
      // dump($data);
      $rs = $GemType2->data($data)->where(array('id'=>$id))->save();
      // dump($rs);die;
      if ($rs > 0) {
        $this->success('修改成功!', U('gemType2'));
      } else {
        $this->error('修改失败!');
      }
      // dump($rs);die;
    } else {
      $this->id = $id;
      $this->name = $name;
      $this->display();
    }
  }
  
  public function priceType()
  {
    $PriceType = M('PriceType');
    $data = $PriceType->select();
    $this->assign('list', $data);
    // dump($data);
    $this->display();
  }
  public function priceTypeUpdate($id='',$name='')
  {
    if(IS_POST) {
      $PriceType = M('PriceType');
      $data['id'] = $id;
      $data['name'] = $name;
      // dump($data);
      $rs = $PriceType->data($data)->where(array('id'=>$id))->save();
      // dump($rs);die;
      if ($rs > 0) {
        $this->success('修改成功!', U('priceType'));
      } else {
        $this->error('修改失败!');
      }
      // dump($rs);die;
    } else {
      $this->id = $id;
      $this->name = $name;
      $this->display();
    }
  }
  
  public function weightType()
  {
    $WeightType = M('WeightType');
    $data = $WeightType->select();
    $this->assign('list', $data);
    // dump($data);
    $this->display();
  }
  public function weightTypeUpdate($id='',$name='')
  {
    if(IS_POST) {
      $WeightType = M('WeightType');
      $data['id'] = $id;
      $data['name'] = $name;
      // dump($data);
      $rs = $WeightType->data($data)->where(array('id'=>$id))->save();
      // dump($rs);die;
      if ($rs > 0) {
        $this->success('修改成功!', U('weightType'));
      } else {
        $this->error('修改失败!');
      }
      // dump($rs);die;
    } else {
      $this->id = $id;
      $this->name = $name;
      $this->display();
    }
  }
  
  public function certificateType()
  {
    $CertificateType = M('CertificateType');
    $data = $CertificateType->select();
    $this->assign('list', $data);
    // dump($data);
    $this->display();
  }
  public function certificateTypeUpdate($id='',$name='')
  {
    if(IS_POST) {
      $CertificateType = M('CertificateType');
      $data['id'] = $id;
      $data['name'] = $name;
      // dump($data);
      $rs = $CertificateType->data($data)->where(array('id'=>$id))->save();
      // dump($rs);die;
      if ($rs > 0) {
        $this->success('修改成功!', U('certificateType'));
      } else {
        $this->error('修改失败!');
      }
      // dump($rs);die;
    } else {
      $this->id = $id;
      $this->name = $name;
      $this->display();
    }
  }


  // 全球猎宝
  public function purchasing()
  {
    $Purchasing = M('Purchasing');
    $data = $Purchasing->select();
    $this->assign('list', $data);
    // dump($data);
    $this->display();
  }
  
  // 用户管理
  public function user()
  {
    $User = M('User');
    $data = $User->select();
    $this->assign('list', $data);
    // dump($data);
    $this->display();
  }

  public function userPwdReset($id='')
  {
    if ($id) {
      $User = M('User');
      // $u = $User->where(array('id'=>$id))->find();

      $pwd = array('password'=>md5('a123456'));
      $rs = $User->where(array('id'=>$id))->data($pwd)->save();
      if ($rs) {
        $this->success('重置成功', U('user'));
      } else {
        $this->error('重置失败', U('user'));
      }
    } else {
      $this->error('参数错误', U('user'));
    }
  }

  public function userUpdate()
  {
    if (IS_POST) {
      $data['id'] = I('post.id');
      $data['nickname'] = I('post.nickname');
      $data['points'] = I('post.points');
      $data['level'] = I('post.level');
      dump($data);
      if (isset($data['id']) && $data['id'] > 0) {
        $User = M('User');
        $rs = $User->where(array('id'=>$data['id']))->data($data)->save();
        if ($rs) {
          $this->success('修改成功', U('user'));
        } else {
          $this->error('修改失败', U('user'));
        }
      } else {
        $this->error('参数错误');
      }
    } else {
      $id = i('get.id');
      if (isset($id) && $id>0) {
        $User = M('User');
        $data = $User->where(array('id'=>$id))->find();
        dump($data);
        $this->user = $data;
        $this->display();
      } else {
        $this->error('参数错误', U('user'));
      }
    }
  }

  public function login($username="", $password="")
  {
    layout(false);
    if (IS_POST) {
      if(strlen(trim($username)) > 0) {
        $Admin = M('Admin');
        $AdminData = $Admin->where(array('uname'=>trim($username)))->select();
        if(sizeof($AdminData) > 0 && $AdminData[0]['pwd'] == $password) {
          session('admin', $AdminData[0]);
          $this->success('登录成功!', U('index'));
        } else {
          $this->error('登录失败!');
        }
        // dump(sizeof($AdminData));die;
      }
      // dump(strlen(trim($username)) > 0);die;
      // if(isset($username))
    } else {
      $this->display();
    }
  }

  public function logout()
  {
    session('admin', null);
    $this->success('退出成功!', U('login'), 1);
  }

  public function save_info()
  {
    $ueditor_config = json_decode(preg_replace("/\/\*[\s\S]+?\*\//", "", file_get_contents("./Public/Ueditor/php/config.json")), true);  
    $action = $_GET['action'];  
    switch ($action) {  
        case 'config':  
            $result = json_encode($ueditor_config);  
            break;  
            /* 上传图片 */  
        case 'uploadimage':  
            /* 上传涂鸦 */  
        case 'uploadscrawl':  
            /* 上传视频 */  
        case 'uploadvideo':  
            /* 上传文件 */  
        case 'uploadfile':  
            $upload = new \Think\Upload();  
            $upload->maxSize = 3145728;  
            $upload->rootPath = './Public/Uploads/';  
            $upload->exts = array('jpg', 'gif', 'png', 'jpeg');  
            $info = $upload->upload();  
            if (!$info) {  
                $result = json_encode(array(  
                        'state' => $upload->getError(),  
                ));  
            } else {  
                $url = __ROOT__ . "/Public/Uploads/" . $info["upfile"]["savepath"] . $info["upfile"]['savename'];  
                $result = json_encode(array(  
                        'url' => $url,  
                        'title' => htmlspecialchars($_POST['pictitle'], ENT_QUOTES),  
                        'original' => $info["upfile"]['name'],  
                        'state' => 'SUCCESS'  
                ));  
            }  
            break;  
        default:  
            $result = json_encode(array(  
            'state' => '请求地址出错'  
                    ));  
                    break;  
    }  
    /* 输出结果 */  
    if (isset($_GET["callback"])) {  
        if (preg_match("/^[\w_]+$/", $_GET["callback"])) {  
            echo htmlspecialchars($_GET["callback"]) . '(' . $result . ')';  
        } else {  
            echo json_encode(array(  
                    'state' => 'callback参数不合法'  
            ));  
        }  
    } else {  
        echo $result;  
    }  
  }
}